package com.leqicheng.tenon;

import java.util.HashMap;
import java.util.Map;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.leqicheng.tenon.log.GetLogIdHttpRequest;
import com.leqicheng.tenon.login.ChannelLoginHttpRequest;
import com.leqicheng.tenon.login.PopLoginWindow;
import com.leqicheng.tenon.model.EntryInfoModel;
import com.leqicheng.tenon.pay.PayInfoModel;
import com.leqicheng.tenon.pay.PopPayWindow;
import com.leqicheng.tenon.share.PopShareWindow;
import com.leqicheng.tenon.util.GeneralCallBack;
import com.leqicheng.tenon.util.RequestStatus;
import com.leqicheng.tenon.util.RequestTypeEnum;
import com.leqicheng.tenon.util.SendShortCutUtil;
import com.leqicheng.tenon.util.SerializableMap;
import com.leqicheng.tenon.util.TenonDB;
import com.leqicheng.tenon.util.WindowStatusCode;

public class TenonPlugin extends CordovaPlugin implements GeneralCallBack {

    private TenonDB mTenonDB;
    private PopLoginWindow mPopLoginWindow;
    private PopPayWindow mPopPayWindow;
    private PopShareWindow mPopShareWindow;
    private Context mContext;
    private CallbackContext mCallbackContext;
    private PopupWindow mPopupWindow;
    private static final String LOG_TAG = "TenonPlugin";

    private Handler mWindowHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == WindowStatusCode.LOGIN_WINDOW_SUCCEED) {
                if (msg.arg1 == 1) {
                    Map<String, Object> resultMap = (Map<String, Object>) msg.obj;
                    if (resultMap != null) {
                        org.json.JSONObject userInfoInJson = new org.json.JSONObject(
                                resultMap);
                        Log.i(LOG_TAG, userInfoInJson.toString());
                        mCallbackContext.success(userInfoInJson);
                    }
                }
                // TODO
                mPopupWindow.dismiss();
            } else if (msg.what == WindowStatusCode.PAY_WINDOW_SUCCEED) {
                Map<String, Object> resultMap = (Map<String, Object>) msg.obj;
                if (resultMap != null) {
                    org.json.JSONObject userInfoInJson = new org.json.JSONObject(
                            resultMap);
                    Log.i(LOG_TAG, userInfoInJson.toString());
                    mCallbackContext.success(userInfoInJson);
                }
                mPopupWindow.dismiss();
            } else if (msg.what == WindowStatusCode.SHARE_WINDOW_SUCCEED) {
                mPopupWindow.dismiss();
            } else if (msg.what == WindowStatusCode.INIT) {
                mPopupWindow.dismiss();
            }
        }
    };
    public static boolean hasRegister = false;

    private void registerInitBroadcast() {
        if (!hasRegister) {
            IntentFilter intentFilter = new IntentFilter();

            intentFilter.addAction("tenon init"); // 为BroadcastReceiver指定action，即要监听的消息名字。

            BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    context.unregisterReceiver(this);
                    hasRegister = false;
                    if (mPopupWindow != null && mPopupWindow.isShowing()) {
                        Message msg = new Message();
                        msg.what = WindowStatusCode.INIT;
                        mWindowHandler.sendMessage(msg);
                    }

                }
            };
            mContext.registerReceiver(myBroadcastReceiver, intentFilter); // 注册监听
            hasRegister = true;
        }
    }

    @Override
    public boolean execute(String action, JSONArray data,
            CallbackContext callbackContext) throws JSONException {
        Log.i(LOG_TAG, "execute enter");
        mCallbackContext = callbackContext;
        mContext = this.cordova.getActivity();
        registerInitBroadcast();
        if (action.equals("pay")) {
            Log.i(LOG_TAG, "execute in pay");
            handlePay(data);
        } else if (action.equals("getUserInfo")) {
            Log.i(LOG_TAG, "execute in getUserInfo");
            if (!EntryInfoModel.getInstance().isEgretGame()) {
                handleLogin();
            }
        } else if (action.equals("getTimeDiffrence")) {
            Log.i(LOG_TAG, "execute in getTimeDiffrence");
            EntryInfoModel model = EntryInfoModel.getInstance();
            Map<String, Object> timeDiffrence = new HashMap<String, Object>();
            timeDiffrence.put("time_diffrence", model.getTimeDiffrence());
            JSONObject timestamp = new JSONObject(timeDiffrence);
            callbackContext.success(timestamp);
        } else if (action.equals("sendToDesk")) {
            Log.i(LOG_TAG, "execute in sendToDesk");
            EntryInfoModel model = EntryInfoModel.getInstance();
            SendShortCutUtil.addShortcutToDesktopAsyn(mContext,
                    model.getGameName(), model.getGameIconUrl(),
                    model.getGameId(), model.getChannelId(),
                    model.getTenonUserId());
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("status", "OK");
            org.json.JSONObject resultInJson = new org.json.JSONObject(result);
            mCallbackContext.success(resultInJson);
        } else if (action.equals("share")) {
            Log.i(LOG_TAG, "execute in share");
            handleShare(data);
        } else if (action.equals("logOut")) {
            Log.i(LOG_TAG, "execute in logOut");
            mTenonDB = new TenonDB(mContext);
            mTenonDB.delete(EntryInfoModel.getInstance().getTenonUserId());
            EntryInfoModel.getInstance().setTenonUserId(null);
            this.mTenonDB = new TenonDB(mContext);
            Intent intent = new Intent();
            intent.setAction("log_init");
            mContext.sendBroadcast(intent);
            if (EntryInfoModel.getInstance().getTenonUserId() == null) {
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("status", "OK");
                org.json.JSONObject resultInJson = new org.json.JSONObject(
                        result);
                Toast.makeText(mContext, "账号已退出，请重新登陆", Toast.LENGTH_SHORT)
                        .show();
                mCallbackContext.success(resultInJson);
            }
            if (!EntryInfoModel.getInstance().isEgretGame()) {
                handleLogin();
            }
        } else if (action.equals("reload")) {
            Intent intent = new Intent();
            intent.setAction("reload_game");
            mContext.sendBroadcast(intent);
        }
        return true;
    }

    private void handleShare(JSONArray data) {
        this.mPopShareWindow = new PopShareWindow(mWindowHandler, mContext,
                null, mCallbackContext, data);
        mPopupWindow = this.mPopShareWindow.getPopupWindow();
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();// 关闭
        } else {
            mPopupWindow.showAtLocation(
                    ((CordovaActivity) this.cordova.getActivity()).getRoot(),
                    Gravity.BOTTOM, 0, 0);
        }
    }

    private void handlePay(JSONArray data) {
        this.mPopPayWindow = new PopPayWindow(mContext, mWindowHandler, data);
        mPopupWindow = this.mPopPayWindow.getPopupWindow();
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();// 关闭
        } else {
            mPopupWindow.showAtLocation(
                    ((CordovaActivity) this.cordova.getActivity()).getRoot(),
                    Gravity.CENTER, 0, 0);
        }
    }

    private void handleLogin() {
        this.mPopLoginWindow = new PopLoginWindow(mContext, mWindowHandler);
        mPopupWindow = this.mPopLoginWindow.getPopupWindow();
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();// 关闭
        } else {
            mPopupWindow.showAtLocation(this.cordova.getActivity().getWindow()
                    .getDecorView(), Gravity.CENTER, 0, 0);
        }
    }

    @Override
    public void onComplete(RequestTypeEnum requestType, int status,
            String responseBody) {
        switch (status) {
        case RequestStatus.NETWORK_ERROR:
            Toast.makeText(mContext, "网络错误", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
        }
    }

}
